from flask import Flask, Blueprint, jsonify, request

app = Flask(__name__)

user_router = Blueprint("user", __name__, url_prefix="/user")

users = []


def ger_user_id():
    return len(users) + 1


@user_router.route("/add", methods=["post", "get"])
def add_user():
    data = request.json
    user_id = ger_user_id()
    user = {
        'id': user_id,
        'username': data.get('username'),
    }
    users.append(user)
    return jsonify(user)


@user_router.route("/list", methods=["get"])
def cases():
    return jsonify(users)


@user_router.route("/list/<int:user_id>", methods=["get"])
def get_user(user_id):
    user = None
    for u in users:
        if u['id'] == user_id:
            user = u
            break

    if user:
        return jsonify(user)
    else:
        return jsonify({'error': '找不到'})


@user_router.route("/update", methods=["post", "get"])
def update_user(user_id):
    data = request.json
    user = None
    for u in users:
        if u['id'] == user_id:
            user = u
            break

    if user:
        user.update({
            'username': data.get('username', user['username']),
        })
        return jsonify(user)
    else:
        return jsonify({'error': '找不到'})


@user_router.route("/delete", methods=["delete", "get"])
def delete_user(user_id):
    global users
    user = None
    for u in users:
        if u['id'] == user_id:
            user = u
            break

    if user:
        users = [u for u in users if u['id'] != user_id]
        return jsonify({'success': 'User deleted'})
    else:
        return jsonify({'error': '用户不存在'})


if __name__ == '__main__':
    app.register_blueprint(user_router)
    app.run()
    ger_user_id()
